package util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.lang.StringEscapeUtils;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class ParserHandler extends DefaultHandler {

    public boolean parseDocument(String filename) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser;
        File fileToParser = new File(filename);

        try {
            parser = spf.newSAXParser();          
             XMLReader xmlReader = parser.getXMLReader();
            
             xmlReader.setContentHandler((ContentHandler) this);
             // Trying to add root element
             Enumeration<InputStream> streams = Collections.enumeration(
             Arrays.asList(new InputStream[]{
             new ByteArrayInputStream("<TopNode>".getBytes()),
             new FileInputStream(fileToParser),//bogus xml
             new ByteArrayInputStream("</TopNode>".getBytes()),}));
             SequenceInputStream seqStream = new SequenceInputStream(streams);
             //InputStream inputStream = new ByteArrayInputStream(seqStream.toString().getBytes( "UTF-8" ) );
             Reader reader = new InputStreamReader(seqStream,"ISO-8859-1");
             InputSource is = new InputSource(reader);
             is.setCharacterStream(reader);
             is.setEncoding("ISO-8859-1");
             xmlReader.parse(is);
            return true;
        } catch (ParserConfigurationException e) {
            System.out.println("ParserConfigurationException in ParserHandler: " + e);
            return false;
        } catch (SAXException e) {
            System.out.println("SAXException in ParserHandler: " + e);
            return false;
        } catch (IOException e) {
            System.out.println("IOException in ParserHandler: " + e);
            return false;
        }
    }
}
